package com.maple.phoneward.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.custom.lockpattern.LockLayer;
import com.maple.phoneward.custom.lockpattern.LockPatternUtils;
import com.maple.phoneward.custom.lockpattern.LockPatternView;
import com.maple.phoneward.custom.lockpattern.LockPatternView.Cell;
import com.maple.phoneward.custom.lockpattern.LockPatternView.OnPatternListener;
import com.maple.phoneward.utils.AppUtil;
import com.maple.phoneward.utils.Md5Util;
import com.maple.phoneward.utils.StringUtil;

/**
 * LockPatternActivity.java
 * 
 * @author: YaJian Qiu
 * @Time 2013-3-26 上午9:34:28<br>
 *       本类描述: 解锁图案绘制界面
 */
public class LockPatternActivity extends Activity implements OnPatternListener {

	private TextView topTextView, bottomTextView;
	private Button leftButton;//, rightButton;
	private RelativeLayout centerLayout;
	private LockPatternView lockPatternView;
	private boolean isFirstStart;// 是否第一次启动程序
	private boolean isLockModel;// 是否是锁定手机模式
	private int drawRightCount = 0;// 绘制图案正确的次数
	private LockLayer lockLayer;
	private LinearLayout buttonLayout;
	private String phonewardPwd;// 防盗密码
	private boolean flag = false;// 认证界面，false代表图案绘制，true代表密码输入

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppUtil.setFullScreen(this);// 设置全屏显示
		// setContentView(R.layout.lockpattern);

		View lock = View.inflate(this, R.layout.lockpattern, null);
		lockLayer = LockLayer.getInstance(this);
		lockLayer.setLockView(lock);

		topTextView = (TextView) lock.findViewById(R.id.lockpattern_top_view);
		bottomTextView = (TextView) lock.findViewById(R.id.lockpattern_bottom_view);
		leftButton = (Button) lock.findViewById(R.id.lockpattern_ok);
		//rightButton = (Button) lock.findViewById(R.id.lockpattern_cancel);
		lockPatternView = (LockPatternView) lock.findViewById(R.id.lockpattern_view);
		buttonLayout = (LinearLayout) lock.findViewById(R.id.lockpattern_button_layout);
		centerLayout = (RelativeLayout) lock.findViewById(R.id.lockpattern_layout);
		lockPatternView.setOnPatternListener(this);// 设置监听

	}

	@Override
	protected void onResume() {
		super.onResume();
		lockLayer.lock();// 锁定屏幕
		// 如果防盗密码已经设置，则左按钮显示为“输入防盗密码”
		phonewardPwd = AppUtil.getFromSharedPreferences(this, Constants.CONFIG_PHONEWARD_PASSWORD, String.class);
		if (StringUtil.isNotEmpty(phonewardPwd)) {
			leftButton.setText(R.string.input_phoneward_pwd);
		}
	
		// 是否是第一次启动
		isFirstStart = AppUtil.getFromSharedPreferences(this, Constants.IS_FIRST_START, true, Boolean.class);
		if (isFirstStart) {
			topTextView.setText(R.string.lock_pattern_top_text_first);
			bottomTextView.setText(R.string.lock_pattern_bottom_text_first);
		} else {
			topTextView.setText(R.string.lock_pattern_top_text);
			bottomTextView.setText(R.string.lock_pattern_bottom_text);
		}
		isLockModel = AppUtil.getFromSharedPreferences(this, Constants.IS_LOCK_MODEL, Boolean.class);
		if (isLockModel) {
			buttonLayout.setVisibility(View.INVISIBLE);
			bottomTextView.setText(R.string.lock_pattern_bottom_text_locked);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		lockLayer.unlock();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		lockLayer.unlock();
	}

	@Override
	public void onAttachedToWindow() {
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
		super.onAttachedToWindow();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:// 屏蔽返回键
			return true;
		case KeyEvent.KEYCODE_HOME:// 屏蔽HOME键
			return true;
		case KeyEvent.KEYCODE_POWER:// 屏蔽电源键
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onPatternStart() {
		// 图案绘制开始时调用，只调一次
		topTextView.setText(R.string.lock_pattern_top_text_done);
	}

	@Override
	public void onPatternCleared() {
	}

	@Override
	public void onPatternCellAdded(List<Cell> pattern) {
		// 每绘制一个点时调用
	}

	@Override
	public void onPatternDetected(List<Cell> pattern) {
		// 绘制完毕时调用，只调一次
		if (pattern.size() >= 4) {
			lockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);
			String lockPattern = LockPatternUtils.patternToString(pattern);
			if (isFirstStart) {
				firstSetLockPattern(lockPattern);
			} else {
				compareLockPattern(lockPattern);
			}
		} else {
			showWrongModel(R.string.lock_pattern_limit);
		}

	}

	/**
	 * 认证通过时保存当前号码
	 */
	private void saveCurrentPhoneNum() {
		AppUtil.saveToSharedPreferences(this, Constants.CONFIG_PHONE_NUMBER,AppUtil.getPhoneNumber(this));
	}
	
	/**
	 * 比较已保存的图案和绘制的图案
	 * 
	 * @param lockPattern
	 * @return
	 */
	private void compareLockPattern(String lockPattern) {
		String existLockPattern = AppUtil.getFromSharedPreferences(this, Constants.LOCK_PATTERN, String.class);
		if (lockPattern.equals(existLockPattern)) {
			verfityRight();
		} else {
			showWrongModel(R.string.lock_pattern_top_text_wrong);
		}
	}

	/**
	 * 认证正确
	 */
	private void verfityRight() {
		saveCurrentPhoneNum();
		if (isLockModel) {
			// 锁定手机模式，直接结束当前Activity即可
			AppUtil.saveToSharedPreferences(this, Constants.IS_LOCK_MODEL,false);
			this.finish();
		} else {
			showActivity(MainActivity.class);// 显示程序主界面
		}
	}

	/**
	 * 显示绘制错误界面模式和提示
	 */
	private void showWrongModel(int resid) {
		topTextView.setText(resid);
		lockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
		// lockPatternView.postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// lockPatternView.clearPattern();
		// }
		// }, 2000);
	}

	/**
	 * 第一次使用程序时设置解锁图案
	 */
	private void firstSetLockPattern(String lockPattern) {
		drawRightCount++;
		if (drawRightCount == 1) {
			topTextView.setText(R.string.lock_pattern_top_text_second);
			AppUtil.saveToSharedPreferences(this, Constants.LOCK_PATTERN, lockPattern);
		} else {
			String preLockPattern = AppUtil.getFromSharedPreferences(this, Constants.LOCK_PATTERN, String.class);
			if (lockPattern.equals(preLockPattern)) {
				topTextView.setText(R.string.lock_pattern_top_text_second_right);
				// 设置第一次启动为false
				AppUtil.saveToSharedPreferences(this, Constants.IS_FIRST_START, false);
				showActivity(MainActivity.class);// 显示程序主界面
			} else {
				drawRightCount = 0;
				topTextView.setText(R.string.lock_pattern_top_text_second_wrong);
			}
		}
	}

	/**
	 * 显示程序界面
	 * 
	 * @param clazz
	 */
	private void showActivity(Class<?> clazz) {
		this.finish();
		if (clazz != null) {
			Intent intent = new Intent(this, clazz);
			startActivity(intent);
		}
	}

	/**
	 * 监听取消按钮的点击事件
	 * 
	 * @param view
	 */
	public void cancel(View view) {
		this.finish();
	}

	/**
	 * 监听重新输入按钮的点击事件
	 * 
	 * @param view
	 */
	public void reDraw(View view) {
		Button btn = (Button) view;
		if (flag) {
			flag = false;// 当前显示图案绘制界面
			centerLayout.removeAllViews();
			centerLayout.addView(lockPatternView);
			btn.setText(R.string.input_phoneward_pwd);
			topTextView.setText(R.string.lock_pattern_top_text);
			bottomTextView.setText(R.string.lock_pattern_bottom_text);
			return;
		}

		if (StringUtil.isNotEmpty(phonewardPwd) && !flag) {
			btn.setText(R.string.draw_unlock_pic);
			showPwdInput();
			return;
		}
		if (lockPatternView != null)
			lockPatternView.clearPattern();
	}

	/**
	 * 显示密码输入界面
	 */
	private void showPwdInput() {
		centerLayout.removeAllViews();
		flag = true;// 当前显示的是密码输入界面
		topTextView.setText(R.string.step_1_not_null);
		bottomTextView.setText(R.string.lock_pattern_bottom_text_pwd);
		final View view = LayoutInflater.from(this).inflate(R.layout.phoneward_pwd_input, centerLayout);
		final EditText editText = (EditText) view.findViewById(R.id.phoneward_pwd_input_edit_text);
		Button okBtn = (Button) view.findViewById(R.id.phoneward_pwd_input_ok);
		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String input = editText.getText().toString();
				if (StringUtil.isEmpty(input)) {
					topTextView.setText(R.string.step_1_not_null);
					return;
				}
				if (StringUtil.equals(Md5Util.md5(input), phonewardPwd)) {
					verfityRight();
				} else {
					topTextView.setText(R.string.phoneward_pwd_wrong);
				}

			}
		});

	}
}
